package service4user

import (
	helper2 "Gin-Gorm-boke/boke_common/helper"
	models2 "Gin-Gorm-boke/boke_common/models"
	"Gin-Gorm-boke/boke_common/redis"
	"Gin-Gorm-boke/boke_common/response"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/copier"
	"strconv"
	"time"
)

type UserDto struct {
	Username string `json:"username"`
	Password string `json:"password"`
}
type UserInfoVo struct {
	Id       int    `json:"id"`
	NickName string `json:"nickName"`
	Sex      string `json:"sex"`
	Email    string `json:"email"`
	Avatar   string `json:"avatar"`
}

func Login(c *gin.Context) {
	var userDto UserDto
	if err := c.ShouldBindJSON(&userDto); err != nil {
		response.ResponseBadRequest(c)
		return
	}
	var user models2.User
	err := models2.Db.Model(new(models2.User)).Where("user_name=?", userDto.Username).First(&user).Error
	fmt.Println(user)
	if err != nil {
		response.RespnseLoginError(c)

		return
	}
	if !helper2.AnalysisBcryptPassword(user.Password, userDto.Password) {
		response.RespnseLoginError(c)
		return
	}
	token, _ := helper2.GenerateToken(user.Id)

	redis.SetUserInfo("bloglogin:"+strconv.Itoa(user.Id), user, time.Hour*24)

	if err != nil {
		fmt.Println(err)
	}
	var userInfoVo UserInfoVo
	copier.Copy(&userInfoVo, &user)
	response.ResponseOK(c, gin.H{
		"token":    token,
		"userInfo": userInfoVo,
	})
	return

}

func Logout(c *gin.Context) {
	//token := c.GetHeader("token")
	//if token == "" {
	//	c.JSON(401, gin.H{
	//		"code": 401,
	//		"msg":  "token为空"})
	//	return
	//}
	//userClaim, _ := helper2.AnalysisToken(token)
	//userId := userClaim.UserId
	//models2.RDb.Del(context.Background(), "bloglogin:"+strconv.Itoa(userId))
	//fmt.Println("bloglogin" + strconv.Itoa(userId))
	response.ResponseOK(c, nil)
	return
}
